#include <Ice/Ice.h>
#include <IceStorm/IceStorm.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#include "Monitor.h"

#include <map>

using namespace std;
using namespace Demo;

class Server : public Ice::Application
{
public:

	virtual int run(int, char*[]);
};

int
main(int argc, char* argv[])
{
	Server app;
	return app.main(argc, argv, "sNode.cfg");
}

int
Server::run(int argc, char*[])
{
	if (argc > 1)
	{
		cerr << appName() << ": too many arguments" << endl;
		return EXIT_FAILURE;
	}

	Ice::ObjectPrx obj = communicator()->propertyToProxy("TopicManager.Proxy");
	IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(obj);
	if (!manager)
	{
		cerr << appName() << ": invalid proxy" << endl;
		return EXIT_FAILURE;
	}

	IceStorm::TopicPrx topic;
	try
	{
		topic = manager->retrieve("Weather");
	}
	catch (const IceStorm::NoSuchTopic&)
	{
		try
		{
			topic = manager->create("Weather");
		}
		catch (const IceStorm::TopicExists&)
		{
			cerr << appName() << ": topic exists, please try again." << endl;
			return EXIT_FAILURE;
		}
	}

	Ice::ObjectPrx pub = topic->getPublisher()->ice_oneway();
	MonitorPrx monitor = MonitorPrx::uncheckedCast(pub);

	srand(time(0));
	char buffName[28];
	sprintf(buffName, "Tower_%d", rand()%100);
	long nIndex = 0;
	while (true){
		nIndex += 1;
		Measurement m;
		m.tower = buffName;
		m.uid = nIndex;
		m.temperature = rand() % 1000 * 1.0 / 10;
		monitor->report(m);
		Sleep(1000);
	}
	return EXIT_SUCCESS;
}
